﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ModeloGaleriaNET;
using System.ComponentModel;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ConfigWindow.xaml
    /// </summary>
    public partial class ConfigWindow : Window
    {
        private bool? success;
        DBConnData conn;
        private string originalServer;
        private string originalUser;
        private string originalPassword;
        private string originalSchema;
        private BackgroundWorker worker;
        private bool isTesting;
        private IAuditoria auditoria;
        private int usuario;
        private ManejadorRoles roleManager;

        public ConfigWindow(int u)
        {
            InitializeComponent();
            conn = DBConnData.Instance;
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            auditoria = new AuditoriaBD();
            usuario = u;
            roleManager = ManejadorRoles.Instance;
        }

        public bool? Success
        {
            get { return success; }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            TestConnection();
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _busyIndicator.IsBusy = false;
            if (success == true)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Conexión establecida con éxito", "Conexión correcta", MessageBoxButton.OK, MessageBoxImage.Information);
                auditoria.Mensaje(new object[]{}, TiposAuditoria.Ordinal(TiposAuditoria.TIPO_AUDITORIA.CAMBIAR_DATOS_ACCESO),
                    usuario);
                System.Threading.Thread.Sleep(1000);
            }
            else
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Imposible establecer la conexión con la base de datos.\n    - Revise sus datos de conexión\n    - Compruebe la conexión con la base de datos",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                auditoria.Mensaje(new object[] { }, TiposAuditoria.Ordinal(TiposAuditoria.TIPO_AUDITORIA.ERROR_CAMBIAR_DATOS_ACCESO),
                    usuario);
                System.Threading.Thread.Sleep(1000);
            }

            if (!isTesting)
                Close();
        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (HasChanges())
            {
                if (success == true)
                {
                    if (cbRecordar.IsChecked == true)
                        conn.Save();
                }
                else
                {
                    if (Xceed.Wpf.Toolkit.MessageBox.Show("Ha hecho cambios en los datos de la conexión, ¿desea salir?",
                                        "Descartar cambios",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Question) == MessageBoxResult.No)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void btGuardar_Click(object sender, RoutedEventArgs e)
        {
            if (success == null)
            {
                if (!worker.IsBusy)
                {
                    conn.Server = tbServer.Text;
                    conn.User = tbUsuario.Text;
                    conn.Password = pbPassword.Password;
                    conn.Schema = tbSchema.Text;
                    _busyIndicator.IsBusy = true;
                    isTesting = false;
                    worker.RunWorkerAsync();
                }
            }
            else
                Close();
        }

        private void btTest_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                conn.Server = tbServer.Text;
                conn.User = tbUsuario.Text;
                conn.Password = pbPassword.Password;
                conn.Schema = tbSchema.Text;
                _busyIndicator.IsBusy = true;
                isTesting = true;
                worker.RunWorkerAsync();
            }
        }

        private void TestConnection()
        {
            success = conn.TestConnection();
        }

        private bool HasChanges()
        {
            if (originalServer != tbServer.Text ||
                originalUser != tbUsuario.Text ||
                originalPassword != pbPassword.Password ||
                originalSchema != tbSchema.Text)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void campoObligatorio_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbServer.Text) && !string.IsNullOrWhiteSpace(tbUsuario.Text) &&
                !string.IsNullOrWhiteSpace(pbPassword.Password) && !string.IsNullOrWhiteSpace(tbSchema.Text))
            {
                btTest.IsEnabled = true;
                btAceptar.IsEnabled = true;
            }
            else
            {
                btTest.IsEnabled = false;
                btAceptar.IsEnabled = false;
            }
        }

        private void pbPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbServer.Text) && !string.IsNullOrWhiteSpace(tbUsuario.Text) &&
                !string.IsNullOrWhiteSpace(pbPassword.Password) && !string.IsNullOrWhiteSpace(tbSchema.Text))
            {
                btTest.IsEnabled = true;
                btAceptar.IsEnabled = true;
            }
            else
            {
                btTest.IsEnabled = false;
                btAceptar.IsEnabled = false;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tbServer.Text = originalServer = conn.Server;
            tbUsuario.Text = originalUser = conn.User;
            pbPassword.Password = originalPassword = conn.Password;
            tbSchema.Text = originalSchema = conn.Schema;
        }
    }
}
